package cn.fntop.controller;

import cn.fntop.config.ToEmail;
import cn.fntop.entity.R;
import cn.fntop.utils.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;

/**
 * @author fn
 * @description
 * @date 2023/3/12 21:56
 */
@RestController
@RequestMapping("/email")
public class DemoTestController {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private ToEmail toEmail;
    @Value("${spring.mail.username}")
    private String from;
    @Value("${spring.mail.switch}")
    private Boolean onMail;

    /**
     * 普通邮件发送
     *
     * @return
     */
    @GetMapping("/common")
    public R sendEmail() {
        if (onMail) {
            //发送邮件通知
            String[] tos = toEmail.getTos();
            if (tos != null && tos.length > 0) {
                EmailUtil emailUtil = new EmailUtil(mailSender);
                return emailUtil.commonEmail(toEmail, from);
            }
        }
        return R.fail("发送失败");
    }

    @GetMapping("/html")
    public R sendHtmlEmail() throws MessagingException {
        if (onMail) {
            //发送邮件通知
            String[] tos = toEmail.getTos();
            if (tos != null && tos.length > 0) {
                EmailUtil emailUtil = new EmailUtil(mailSender);
                String html = "<h1>" + "这是个html邮件" + "</h1>";
                toEmail.setContent(html);
                return emailUtil.htmlEmail(toEmail, from);
            }
        }
        return R.fail("发送失败");
    }

    /**
     * @param file
     * @param resId 唯一id，通过
     * @return
     */
    @GetMapping("/static")
    public R sendstaticEmail(MultipartFile file, String resId) {
        if (onMail) {
            //发送邮件通知
            String[] tos = toEmail.getTos();
            if (tos != null && tos.length > 0) {
                EmailUtil emailUtil = new EmailUtil(mailSender);
                return emailUtil.staticEmail(toEmail, file, resId, from);
            }
        }
        return R.fail("发送失败");
    }

    @GetMapping("/attachment")
    public R sendattachmentEmail(MultipartFile file) {
        if (onMail) {
            //发送邮件通知
            String[] tos = toEmail.getTos();
            if (tos != null && tos.length > 0) {
                EmailUtil emailUtil = new EmailUtil(mailSender);
                return emailUtil.enclosureEmail(toEmail, file, from);
            }
        }
        return R.fail("发送失败");
    }

}
